package com.wl.android.flutterdemo

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.idlefish.flutterboost.FlutterBoost
import com.idlefish.flutterboost.FlutterBoostRouteOptions
import com.wl.android.flutterdemo.databinding.ActivityMainBinding


class MainActivity : AppCompatActivity() {

    private var binding: ActivityMainBinding? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(LayoutInflater.from(this)).also { setContentView(it.root) }

        initTitle()
        val arguments: Map<String, Any> = hashMapOf("title" to "MainPage", "showTitle" to true)
        binding?.btnGotoActivity1?.setOnClickListener {
            // Native 启动 Flutter 页面 并通过 onActivityResult 接收返回值
            val options = FlutterBoostRouteOptions.Builder()
                .pageName(FlutterHelper.FLUTTER_PAGE_MAIN)
                .arguments(arguments)
                .requestCode(1000)
                .build()
            FlutterBoost.instance().open(options)
        }

        binding?.btnGotoActivity2?.setOnClickListener {
            val options = FlutterBoostRouteOptions.Builder()
                .pageName(FlutterHelper.FLUTTER_PAGE_CALENDAR)
                .requestCode(1111)
                .build()
            FlutterBoost.instance().open(options)
        }

        binding?.btnGotoActivityTest?.setOnClickListener {
            startActivityForResult(Intent(this, TestActivity::class.java), 2001)
        }
        binding?.btnGotoFlutterTestPage?.setOnClickListener {
            val options = FlutterBoostRouteOptions.Builder()
                .pageName(FlutterHelper.FLUTTER_PAGE_TEST)
                .requestCode(1111)
                .build()
            FlutterBoost.instance().open(options)
        }
    }

    private fun initTitle() {
        binding?.appbar?.titleTv?.text = "首页"
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val resultData = FlutterHelper.getActivityResultData(data)

        if (requestCode == 1000 && resultCode == Activity.RESULT_OK) {
            Toast.makeText(this, "Flutter 返回值: $resultData", Toast.LENGTH_LONG).show()
        } else if (requestCode == 2001 && resultCode == Activity.RESULT_OK) {

            Toast.makeText(this, "Flutter 返回值: ${data?.getStringExtra("msg")}", Toast.LENGTH_LONG).show()
        }
        Log.d("WLTest", "MainActivity onActivityResult requestCode: $requestCode, resultCode: $resultCode data: $resultData")
    }
}